import { Suspense } from 'react';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Plus, Receipt, Building2 } from 'lucide-react';
import { formatMoney, formatDate } from '@/lib/utils';
import { prisma } from '@/lib/prisma';

const expenseTypeMap = {
  material: '材料费',
  labor: '人工费',
  equipment: '设备费',
  other: '其他费用'
} as const;

async function ExpenseList() {
  const expenses = await prisma.expense.findMany({
    include: {
      site: true
    },
    orderBy: {
      paymentDate: 'desc'
    }
  });

  return (
    <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
      {expenses.map((expense) => (
        <Link key={expense.id} href={`/expenses/${expense.id}`}>
          <Card className="hover:bg-muted/50 transition-colors">
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">
                {expenseTypeMap[expense.type]}
              </CardTitle>
              <Receipt className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatMoney(expense.amount)}</div>
              <div className="text-xs text-muted-foreground space-y-1">
                <div className="flex items-center gap-1">
                  <Building2 className="h-3 w-3" />
                  {expense.site.name}
                </div>
                <div>支付时间: {formatDate(expense.paymentDate)}</div>
                {expense.vendor && <div>供应商: {expense.vendor}</div>}
                {expense.description && (
                  <div className="line-clamp-2">备注: {expense.description}</div>
                )}
              </div>
            </CardContent>
          </Card>
        </Link>
      ))}
    </div>
  );
}

export default function ExpensesPage() {
  return (
    <main className="container mx-auto p-4 space-y-4">
      <div className="flex justify-between items-center">
        <h1 className="text-3xl font-bold tracking-tight">支出记录</h1>
        <Button asChild>
          <Link href="/expenses/new">
            <Plus className="mr-2 h-4 w-4" />
            记录支出
          </Link>
        </Button>
      </div>

      <Suspense fallback={<div>加载中...</div>}>
        <ExpenseList />
      </Suspense>
    </main>
  );
} 